/**
 * 
 */
package com.feib.stms.util;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.feib.stms.model.MenuItem;
import com.feib.stms.service.MenuItemService;

/**
 * @author Jimmy Liu
 *
 */
@Service("menuLoader")
@Scope(value=BeanDefinition.SCOPE_SINGLETON)
public class MenuLoader implements Serializable
{
	private static final long serialVersionUID = -1213160675970725850L;
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Resource(name="menuItemService")
	private MenuItemService menuItemService;
    
    private List<MenuItem> menuItems;
    
    private Map<String, MenuItem> menuCaches;
    
    private Map<String, MenuItem> pathCaches;
	
	@PostConstruct
	public void loadMenuItems()
	{
		menuItems = menuItemService.getAllEnabledMenuItemsWithRoles();
		copyToCaches();
	}
	
	private void copyToCaches()
	{
		menuCaches = new TreeMap<String, MenuItem>();
		pathCaches = new TreeMap<String, MenuItem>();
		
		for(MenuItem menuItem : menuItems)
		{			
			if (StringUtils.isNotBlank(menuItem.getActionBeanClass()))
			{
				menuCaches.put(menuItem.getActionBeanClass().toLowerCase(), menuItem);
			}
			
			if (StringUtils.isNotBlank(menuItem.getActionPage()))
			{
				pathCaches.put(menuItem.getActionPage().toLowerCase(), menuItem);
			}
		}
	}

	public List<MenuItem> getMenuItems() {
		return menuItems;
	}
	
	public String getActionNameByPath(String path)
	{
		if (null != path)
		{
			MenuItem menuItem = pathCaches.get(path.toLowerCase());
			if (null != menuItem)
				return menuItem.getActionName();
		}
		
		return null;
	}
	
	public String getActionNameByBeanClass(String className)
	{
		if (null != className)
		{
			MenuItem menuItem = menuCaches.get(className.toLowerCase());
			if (null != menuItem)
				return menuItem.getActionName();
		}
		
		return null;
	}
	
	public String getParentActionNameByBeanClass(String className)
	{
		if (null != className)
		{
			MenuItem menuItem = menuCaches.get(className.toLowerCase());
			if (null != menuItem)
			{
				MenuItem parent = menuItem.getParentMenuItem();
				if (null != parent)
				{
					return parent.getActionName();
				}			
			}
		}
		
		
		return null;
	}
	
	

}
